import AES from 'crypto-js/aes'
import EncUtf8 from 'crypto-js/enc-utf8'
import ECB from 'crypto-js/mode-ecb'
import Pkcs7 from 'crypto-js/pad-pkcs7'

let _secret_key = 'xxaxxb123'

export default {
  // 随机生成指定数量的16进制key
  generateSecretKey (num) {
    const library = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    let key = ''
    for (let i = 0; i < num; i++) {
      const randomPoz = Math.floor(Math.random() * library.length)
      key += library.substring(randomPoz, randomPoz + 1)
    }
    return key
  },

  setSecretKey (key) {
    _secret_key = key
    return this
  },

  getSecretKey () {
    return _secret_key
  },

  /**
   * 加密
   * @param  content  加密文本
   * @param  keyStr 秘钥
   * @returns
   */
  encrypt (content, secretKey = _secret_key) {
    // 判断是否存在ksy，不存在就用定义好的key
    const key = EncUtf8.parse(secretKey)
    const srcs = EncUtf8.parse(content)
    const encrypted = AES.encrypt(srcs, key, { mode: ECB, padding: Pkcs7 })
    return encrypted.toString()
  },

  /**
   * 解密
   * @param {string} content
   * @param {string} secretKey
   * @returns
   */
  decrypt (content, secretKey = _secret_key) {
    secretKey = EncUtf8.parse(secretKey)
    const decrypt = AES.decrypt(content, secretKey, { mode: ECB, padding: Pkcs7 })
    return EncUtf8.stringify(decrypt).toString()
  }
}